#include <bits/stdc++.h>
using namespace std;
#define yes cout << "YES" << endl
#define no cout << "NO" << endl
using ll = long long;
ll n, m;
const ll N = 777;
ll a[N][N];

bool cnt[770*770];
void solve()
{
    ll ans = 0;
    unordered_set<ll> st;
    memset(cnt, false, sizeof cnt);
    cin >> n >> m;
    ll max = 0;
    for (ll i = 1; i <= n; i++)
    {
        for (ll j = 1; j <= m; j++)
        {
            cin >> a[i][j];
            if (a[i][j] > max)
            {
                max = a[i][j];
            }
            st.insert(a[i][j]);
        }
    }
    if(st.size()==0)
    {
        cout << 0 << endl;
        return;
    }
    ll dx[] = {0, 0, 1, -1};
    ll dy[] = {1, -1, 0, 0};
    ll f = 0;
    for (ll i = 1; i <= n; i++)
    {
        for (ll j = 1; j <= m; j++)
        {
            if (cnt[a[i][j]])
            {
                continue;
            }
            for (ll k = 0; k < 4; k++)
            {
                ll tx = i + dx[k], ty = j + dy[k];
                if (tx < 1 || tx > n || ty < 1 || ty > m || a[tx][ty] != a[i][j])
                {
                    continue;
                }
                else
                {
                    cnt[a[i][j]] = true;
                    f = 1;
                    break;
                }
            }
        }
    }
    for (auto &i : st)
    {
        ans += (cnt[i] ? 2 : 1);
    }
    cout << ans - 1 - f << endl;
}
int main()
{
    int t = 1;
    cin >> t;
    while (t--)
    {
        solve();
    }
    return 0;
}
